##################################################
##  ATENCAO ESSE script soh funciona em Linux   ##
##                by Chaves 2013                ##
##################################################

import sys
import time,datetime
import glob
import os

def execServerLit(command):
    #print command
    execute_command = os.popen(command,"r")
    return execute_command.read()

def getLastTwoFolders():
    # Pega as duas ultimas pastas de arquivos da anatel
    #folders=execServerLit()
    execute_command = os.popen("ls -lt | grep '^d' | awk '{ print $9 }' | grep '^[0-9]*$' | head -2","r")
    folders_arr = []
    for line in execute_command.readlines():
        if len(line)>0:
            folders_arr.append(line[:-1])
    return folders_arr

def getSize(file_path):
    size=execServerLit('du -b %s | grep -o -E "^[0-9]*"' % (file_path))
    if not len(size)>0:
        try:
            raise NameError('HiThere')
        except NameError:
            print 'An exception flew by!'
            raise
    else:        
        return size[:-1]

def getMd5Hash(file_path):
    #verifica o md5 do arquivo de dentro do zip 
    md5hash=execServerLit('unzip -p %s | md5sum -t | grep -o -E "^[0-9a-f]*"' % (file_path))
    #print "%s %s" % (md5hash[:-1],file_path)
    if not len(md5hash)>0:
        try:
            raise NameError('HiThere')
        except NameError:
            print 'An exception flew by!'
            raise
    else:        
        return md5hash[:-1]

def unzip(zipfilepath,new_path,filename):
    if not os.path.exists(os.curdir + "/" + new_path):
        os.makedirs(os.curdir + "/" + new_path)
    #verifica o md5 do arquivo de dentro do zip 
    unzip=execServerLit('unzip -p %s > %s%s' % (zipfilepath,new_path,filename))

 
if __name__ == '__main__':
    if not len(sys.argv) < 2:
        
        for v in sys.argv:
            if len(v.split("="))>1:
                param = v.split("=")[0].strip()
                valor = v.split("=")[1].strip()
                try:
                    if param.lower().strip().find("arquivo_fix")>-1:
                        arquivo_fix = valor
                        print "arquivo_fix: %s" % (arquivo_fix)
                        date_now = datetime.strptime(arquivo_fix.split('_')[0], '%Y-%m-%d')                       
                    else:
                        eval('%s=%s' % (param,valor))   
                except:
                    exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
                    print "%s:%s" % (exceptionType,exceptionValue)
    
    
    start_total = time.time()
    
    print "(Comecando!)"
    

    print (os.curdir + "/" + getLastTwoFolders()[0] + "/*.zip")
    
    last_down_folders = getLastTwoFolders()
    if len(last_down_folders)==2:
        for zipfile in glob.glob(os.curdir + "/" + last_down_folders[0] + "/*.zip"):            
            
            newer_file = getSize(zipfile)
            newer_md5 = getMd5Hash(zipfile)
            try:
                older_file = getSize(str(zipfile).replace(last_down_folders[0], last_down_folders[1]))
                older_md5 = getMd5Hash(str(zipfile).replace(last_down_folders[0], last_down_folders[1]))
            except NameError:
                print "Par de arquivo inexistente para: %s" % (zipfile)
            
            diff = int(older_file) - int(newer_file)
            
            if diff:
                print "Diferenca: %s Novo(%s) Velho(%s) Arquivo:'%s'" % (diff,newer_file,older_file,zipfile)
                
                process_word = "process" #pasta que vai conter os processos 
                estado = str(zipfile).split("/")[-1][0:2].upper()
                new_path = process_word + "/" + last_down_folders[0] + "_" + last_down_folders[1] + "/" + estado + "/"
                
                unzip(str(zipfile),new_path,str(zipfile).split("/")[-1].replace(".zip",".txt") + "_" + "new")                 
                unzip(str(zipfile).replace(last_down_folders[0], last_down_folders[1]),new_path,str(zipfile).split("/")[-1].replace(".zip",".txt") + "_" + "old")
                
            if str(newer_md5)==str(older_md5):
                print "MD5 Matches: md5(%s) %s" % (newer_md5,zipfile)
            

                
            
            
            
            
            

            
    else:
        print "Ultimas duas pastas inexistentes ou com erro!"
    
    
    print "(Total Tempo Gasto: %s)" % ((time.time() - start_total))
